<?php

namespace App\Model\Common;
use PHPMailer\PHPMailer\PHPMailer;
use App\Model\Common\EmailLog;

class Email
{
    public $Mailer;
    protected $charset = 'UTF-8';

    public function __construct()
    {
        $Mailer = new PHPMailer();
        $Mailer->isSMTP();
        $Mailer->SMTPAuth = true;
        $Mailer->Host = env('MAIL_HOST');
        $Mailer->CharSet = $this->charset;
        $Mailer->Username = env('MAIL_USERNAME');
        $Mailer->Password = env('MAIL_PASSWORD');
        $Mailer->Port = env('MAIL_PORT');
        $Mailer->SMTPSecure = 'ssl';
        $Mailer->setFrom(env('MAIL_USERNAME'), env('MAIL_POSTERNAME'));
        $Mailer->isHTML(true);
        $this->Mailer = $Mailer;
    }

    public function sendMail($type, $email, $param = [])
    {
        if (!$this->checkFrequency($type, $email,$param['code'])) {
            return false;
        }
        $this->Mailer->addAddress($email);
        switch ($type) {
            case 'register':
                $this->Mailer->Subject = 'Register';
                $url = env('APP_URL') . 'user/register?token='.$param['code'].'&email='.$email;
                $this->Mailer->Body = $this->getMailBody($email, $url, 'sign up');
                break;
            case 'login':
                $this->Mailer->Subject = 'Login';
                $url = env('APP_URL') . 'user/quickLogin?token='.$param['code'].'&email='.$email;
                $this->Mailer->Body = $this->getMailBody($email, $url, 'sign in');
                break;
            case 'findpassword':
                $this->Mailer->Subject = 'Find Password';
                $url = env('APP_URL') . 'user/findPwd?token='.$param['code'].'&email='.$email;
                $this->Mailer->Body = $this->getMailBody($email, $url, 'reset password');
                break;
            case 'oldemail':
                $this->Mailer->Subject = 'Old Email Verify';
                $url = env('APP_URL').'user/oldEmailVerify?token='.$param['code'].'&email='.$email;
                $this->Mailer->Body = $this->getMailBody($email, $url, 'change email');
                break;
            case 'newemail':
                $this->Mailer->Subject = 'New Email Verify';
                $url = env('APP_URL').'user/newEmailVerify?token='.$param['code'].'&email='.$email;
                $this->Mailer->Body = $this->getMailBody($email, $url, 'change email');
                break;
            default:
                break;
        }
        try {
            $re = $this->Mailer->send();
            if (false == $re) {
                $this->error = $this->getEmailError();
                return false;
            }
            return true;
        } catch (\Exception $e) {
            $this->error = $this->getEmailError();
            return false;
        }
    }

    public function getError()
    {
        return $this->error;
    }

    public function getEmailError()
    {
        return $this->Mailer->ErrorInfo;
    }
    
    //请求频次检测
    private function checkFrequency($type, $email, $code)
    {
        $EmailLog = new EmailLog();
        $ip = request()->ip();
        $ltime = time() - 3600;
        $ltime = date('Y-m-d H:i:s', $ltime);

        $ct = $EmailLog->where('type', $type)->where('create_time', '>', $ltime)->where(function ($query) use ($email, $ip) {
            $query->where('email', $email)->whereOr('ip', $ip);
        })->count();
        if ($ct > 20) {
            $this->error = lang('10010');

            return false;
        }
        $EmailLog->ip = $ip;
        $EmailLog->email = $email;
        $EmailLog->type = $type;
        $EmailLog->code = $code;
        $EmailLog->save();

        return true;
    }

    public function getMailBody($userName, $verifyEmailUrl, $action)
    {
        $html = <<< STR
        <html>
        <head>
            <meta http-equiv="content-type" content="text/html;charset=utf-8">
        </head>
        </body>
        <div class="email-content-wrapper" style="width: 100%;">
        <div class="center" style="width: 700px; margin:0 auto; -webkit-font-smoothing: antialiased;font-family:'SF Pro Text','SF Pro Icons','Helvetica Neue','Helvetica','Arial',sans-serif">
        <h1 style="margin:20px 0 15px 0; font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif">
        <a style="color: #012f50; text-decoration: none;" href=" ">HaYiiRo</a >
        </h1>
        <div class="content" style="font-size: 17px; padding: 20px 0; border-top: 1px solid #d3d3d3; border-bottom: 1px solid #d3d3d3;">
        <p style="margin: 0; line-height: 2.5;">Hello, <strong>{$userName}</strong></p >
        <p style="margin: 0; line-height: 2.5;">To complete {$action}, click the link below to verify your email.</p >
        <a href="{$verifyEmailUrl}" style="display: block; width: 130px; height: 35px; line-height: 35px; text-align: center; text-decoration: none; color: #fff; background-color: #06a2ea; border-radius: 5px; margin: 10px 0;">Verify Email</a>
        <p style="margin: 0; line-height: 2.5;">If this button does not work, you can copy the following links to your browser.</p>
        <p style="line-height: 2; font-size: 14px; color: blue; text-align: left;">{$verifyEmailUrl}</p>
        <p style="margin: 0; line-height: 2.5;">If you didn't {$action} for this, just ignore this email.</p >
        </div>
        <p style="line-height: 2; font-size: 14px; color: #96959b; text-align: right;">Please email us at <a href="mailto:296337052@qq.com">296337052@qq.com</a > if you have any questions.</p >
        </div>
        </div>;
        </body>
        </html>
STR;

        return $html;
    }
}
